package com.ai.nsa.utils.partition;

/**
 * @author Feng Chen
 */
public class HashPartitioner extends Partitioner {

    private final static int DEFAULT_PARTITION_AMOUNT = 8;

    public HashPartitioner() {
        this(DEFAULT_PARTITION_AMOUNT);
    }

    public HashPartitioner(int numPartitions) {
        this.numPartitions = numPartitions;
    }

    @Override
    public int getPartition(String key) {

        if (key == null) {
            return 0;
        }

        return nonNegativeMod(key.hashCode(), numPartitions);
    }


    // SECTION: INNER HELPER

    public int nonNegativeMod(int dividend, int divisor) {
        int rawMod = dividend % divisor;
        return rawMod + (rawMod < 0 ? divisor : 0);
    }

}
